/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUIChessMan.java
 *
 * Created on Apr 15, 2011, 4:13:20 PM
 */
package horsechess.client.gui;

import horsechess.client.data.ChessBoardData;
import horsechess.client.data.ChessManData;
import horsechess.client.handle.ChessMan;
import horsechess.client.data.PlayerData;
import horsechess.client.handle.ChessBoard;
import horsechess.util.Point;
import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author Administrator
 */
public class GUIChessMan extends JPanel {

    private JPanel pnlChessboard;
    private GUIClient uiClient;

    /** Creates new form GUIChessMan */
    public GUIChessMan() {
        this.setLayout(null);
        picChessMan = new JLabel();
        stateClick = false;
        picChessMan.setBounds(8, 8, 33, 33);
        picChessMan.addMouseListener(new java.awt.event.MouseAdapter() {

            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                picChessManMouseClicked(evt);
            }
        });
        this.add(picChessMan);
    }

    public GUIChessMan(Point p, int color) {
        initComponents();
        getImageChessMan(color);
        try {
            picChessMan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/horse/" + fileName)));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "The image of the horse cannot found?", "Error", JOptionPane.ERROR_MESSAGE);
        }
        picChessMan.setBounds(p.getX(), p.getY(), 33, 33);
        stateClick = false;
    }

    public void setUiClient(GUIClient uiClient) {
        this.uiClient = uiClient;
    }

    /**
     * get Image of chessman based on value of dice
     * @param m
     * @return
     */
    public String getImageChessMan(int m) {
        switch (m) {
            case 1:
                fileName = "GREEN.gif";
                break;
            case 2:
                fileName = "RED.gif";
                break;
            case 3:
                fileName = "YELLOW.gif";
                break;
            case 4:
                fileName = "BLUE.gif";
                break;
        }
        return fileName;
    }

    public void setChessboard(JPanel pnl) {
        this.pnlChessboard = pnl;
    }

    /**
     * Check battle value
     * @return
     */
    public boolean chkStartBattleValue() {
        if (chessBoard.getDiceNumber() == 1) {
            if (chessBoard.getDiceValue1() == 1
                    || chessBoard.getDiceValue1() == 6) {
                return true;
            }
        } else {
            if ((chessBoard.getDiceValue1() == 1 && chessBoard.getDiceValue2() == 1)
                    || (chessBoard.getDiceValue1() == 2 && chessBoard.getDiceValue2() == 2)
                    || (chessBoard.getDiceValue1() == 3 && chessBoard.getDiceValue2() == 3)
                    || (chessBoard.getDiceValue1() == 4 && chessBoard.getDiceValue2() == 4)
                    || (chessBoard.getDiceValue1() == 5 && chessBoard.getDiceValue2() == 5)
                    || (chessBoard.getDiceValue1() == 6 && chessBoard.getDiceValue2() == 6)) {
                return true;
            }
            if ((chessBoard.getDiceValue1() == 1 && chessBoard.getDiceValue2() == 6)
                    || (chessBoard.getDiceValue1() == 6 && chessBoard.getDiceValue2() == 1)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Check whether the horse can go further or not
     * @param dice
     * @param posOnBoard
     * @return
     */
    public boolean checkMoved(int dice, int posOnBoard) {
        for (int i = 1; i < dice; i++) {
            if (chessBoard.arrChessBoard[(posOnBoard + i) % 56] != 0) {
                return false;// cannot go further
            }
        }
        return true;
    }

    /**
     * Show up chessman 
     * @param m
     */
    public void showUp(int m) {

        getImageChessMan(m);
        //System.out.println(fileName);
        picChessMan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/horse/" + fileName)));
    }

    /**
     * Load image of chessman
     */
    public void loadImageChessMan(ImageIcon icon) {
        picChessMan.setIcon(icon);
    }

    /**
     * Get vi tri ve` dich cua chessman
     * @return
     */
    public int getChessManFinishes() {
        PlayerData player = chessBoard.players.get(chessMan.getColorChess() - 1);
        return player.getFinalChessMan();
    }

    /**
     * Process moving the horse
     */
    public int checkMoving() {

        if (chessMan == null) {
            //System.out.println("Ko co du lieu quan co");
        }
        if (chessMan.getPositionOnBoard() == -1) {
            if (this.chkStartBattleValue() == true) {
                if (chessBoard.arrChessBoard[chessMan.getStartBattleValue()] != chessMan.getColorChess()) {
                    return 1;
                }
            }
        } else {
            int value = chessBoard.getDiceValue();
            //if()
            if (chessMan.getPositionOnBoard() == chessMan.getPositionFinal()) {
                //int n = getChessManFinishes();
                //System.out.println("Position at final point cell number : " + n);
                if (chkStartBattleValue() == true) //&& chessMan.getBac() == 0) {
                {
                    PlayerData player = (PlayerData) chessBoard.players.get(chessMan.getColorChess() - 1);
                    try {
                        // Vi tri dau tien ve dich thi` dc 20 diem tiep theo cong them 10
                        if (player.isHorseJoin(chessMan.getFinalCage())) {
                            return 1;
                        } else {
                            return 0;
                        }
                        // chessMan.setBac(n);
                    } catch (IndexOutOfBoundsException ex) {
                        //horsechess.client.gui.GUIClient.lblMessage.setText("This horse have already encountered final position");
                        return 0;
                    }
                } else {
                    return 0;
                }
            } else if (chessMan.getCount() + value > chessBoard.getNumberCellBoard()) {
                return 0;
            }

            if (this.checkMoved(value, chessMan.getPositionOnBoard())) {
                if (chessBoard.arrChessBoard[(chessMan.getPositionOnBoard() + value) % 56] != chessMan.getColorChess()) {
                    return 1;
                }

            }
        }
        return 0;
    }

    public int executingMoving() {

        if (chessMan.getPositionOnBoard() == -1) {
            if (this.chkStartBattleValue() == true) {
                if (chessBoard.arrChessBoard[chessMan.getStartBattleValue()] != chessMan.getColorChess()) {

                    if (chessBoard.arrChessBoard[chessMan.getStartBattleValue()] != 0) {
                        kickChessMan(chessMan.getStartBattleValue());
                        updateScore(5);
                    }
                    chessMan.setPositionOnBoard(chessMan.getStartBattleValue());
                    //System.out.println("Position on board: " + chessMan.getPositionOnBoard());
                    chessBoard.arrChessBoard[chessMan.getPositionOnBoard()] = chessMan.getColorChess();
                    chessMan.setCount(chessMan.getCount() + 1);
                    ChessBoard cb = new ChessBoard();
                    Point p = cb.getPosition(chessMan.getPositionOnBoard());
                    picChessMan.setBounds(p.getX(), p.getY(), 33, 33);
                    updateScore(3);
                    return 1;
                }
            }
        } else {
            int value = chessBoard.getDiceValue();
            //if()
            if (chessMan.getPositionOnBoard() == chessMan.getPositionFinal()) {
                //int n = getChessManFinishes();
                //System.out.println("Position at final point cell number : " + n);
                if (chkStartBattleValue() == true) //&& chessMan.getBac() == 0) {
                {
                    PlayerData player = (PlayerData) chessBoard.players.get(chessMan.getColorChess() - 1);
                    try {

                        // Vi tri dau tien ve dich thi` dc 20 diem tiep theo cong them 10
                        if (player.isHorseJoin(chessMan.getFinalCage())) {
                            Point p = (Point) player.listOfFinalPosition.get(chessMan.getFinalCage());
                            picChessMan.setBounds(p.getX(), p.getY(), 33, 33);
                            if(chessMan.getFinalCage()!=0)
                             player.horseInFinals.set(chessMan.getFinalCage()-1, null);
                            player.horseInFinals.set(chessMan.getFinalCage(), picChessMan);

                            if (chessMan.getFinalCage() == 0) {
                                updateScore(20);
                            } else {
                                updateScore(10);
                            }
                            chessBoard.arrChessBoard[chessMan.getPositionOnBoard()] = 0;
                            player.setFinalChessMan(player.getFinalChessMan() + 1);
                        } else {
                            return 0;
                        }
                        chessMan.setFinalCage(chessMan.getFinalCage()+1);
//                        if (chessMan.getFinalCage() == 6) {
//                            finalCage = 0;
//                        }
                        return 1;

                    } catch (IndexOutOfBoundsException ex) {
                        horsechess.client.gui.GUIClient.lblMessage.setText("This horse have already encountered final position");
                        return 0;
                    }
                } else {
                    return 0;
                }
            } else if (chessMan.getCount() + value > chessBoard.getNumberCellBoard()) {
                return 0;
            }

            if (this.checkMoved(value, chessMan.getPositionOnBoard())) {
                if (chessBoard.arrChessBoard[(chessMan.getPositionOnBoard() + value) % 56] != chessMan.getColorChess()) {
                    if (chessBoard.arrChessBoard[(chessMan.getPositionOnBoard() + value) % 56] != 0) {
                        kickChessMan((chessMan.getPositionOnBoard() + value) % 56);
                        updateScore(5);
                    }
                    chessBoard.arrChessBoard[chessMan.getPositionOnBoard()] = 0;
                    chessMan.setPositionOnBoard(chessMan.getPositionOnBoard() + value);
                    chessMan.setPositionOnBoard(chessMan.getPositionOnBoard() % 56);
                    chessBoard.arrChessBoard[chessMan.getPositionOnBoard()] = chessMan.getColorChess();
                    chessMan.setCount(chessMan.getCount() + chessBoard.getDiceValue());
                    ChessBoard cb = new ChessBoard();
                    Point p = cb.getPosition(chessMan.getPositionOnBoard());

                    picChessMan.setBounds(p.getX(), p.getY(), 33, 33);
                    return 1;
                }
            }
        }
        return 0;
    }

    public boolean checkMoveInFinalPos(Point p) {
        Component[] components = pnlChessboard.getComponents();
        for (int i = 0; i < components.length; i++) {
            Component component = components[i];
            if (component instanceof JLabel) {
                JLabel picHorse = (JLabel) component;
                int x = (int) picHorse.getBounds().getX();
                int y = (int) picHorse.getBounds().getX();

                if (p.getX() == x || p.getY() == y) {
                    System.out.println(new Point(x, y).toString() + "Ngua: " + picHorse.getToolTipText());
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Kick the chessman got 5 point
     * @param posOnBoard
     */
    public void kickChessMan(int posOnBoard) {
        int chessMan = chessBoard.arrChessBoard[posOnBoard];
        System.out.println("Chessman kick: " + chessMan);
        PlayerData player = (PlayerData) chessBoard.players.get(chessMan - 1);
        for (int i = 0; i < player.getNumberOfChessMan(); i++) {
            ChessMan cm = (ChessMan) player.listOfChessMan.get(i);
            if (cm.getChessman().getPositionOnBoard() == posOnBoard) {
                Point p = cm.getChessman().getPositionInCage();
                cm.getGUIChessMan().picChessMan.setBounds(p.getX(), p.getY(), 33, 33);
                cm.getChessman().setPositionOnBoard(-1);

                return;
            }
        }

    }

    public void updateScore(int score) {
        int posOfPlayer = chessBoard.players.indexOf(player);
        System.out.println("Index of player: " + posOfPlayer);
        player.setScore(player.getScore() + score);
        chessBoard.players.set(posOfPlayer, player);
        GUIClient.uIClient.updateScore();
    }

    public Boolean getStateClick() {
        return stateClick;
    }

    public void setStateClick(Boolean stateClick) {
        this.stateClick = stateClick;
    }

    public JLabel getPicChessMan() {
        return picChessMan;
    }

    public void setPicChessMan(JLabel picChessMan) {
        this.picChessMan = picChessMan;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

    
    }// </editor-fold>//GEN-END:initComponents

    private void picChessManMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_picChessManMouseClicked
        if (GUIClient.uIClient.lblEndingMessage.getText().equals("YOUR TURN")) {
            processMoving();
        } else {
            uiClient.lblMessage.setText("It's not your turn");
        }
    }//GEN-LAST:event_picChessManMouseClicked

    public void processMoving() {
        if (player == null) {
            horsechess.client.gui.GUIClient.lblMessage.setText("It's not your turn!!");
        }
        if (stateClick == true) {
            if (executingMoving() == 1) {
                horsechess.client.gui.GUIClient.lblMessage.setText("Horse " + picChessMan.getToolTipText() + " of " + player.getUsername() + " has been moved " + chessBoard.getDiceValue() + " cell.Please roll the dice!!.");
                stateClick = false;
                GUIClient.uIClient.player.position(player.getUsername(), Integer.parseInt(picChessMan.getToolTipText().trim()));
                for (int i = 0; i < player.getNumberOfChessMan(); i++) {
                    ChessMan chessMan = (ChessMan) player.listOfChessMan.get(i);
                    if (chessMan.getGUIChessMan().getStateClick()) {
                        chessMan.getGUIChessMan().setStateClick(false);
                    }

                }
//                if (uiClient == null) {
//                    System.out.println("Null UI roi !@@@@@@@@@@@@@@@@@@@");
//                }

                uiClient.turnToNextPlayer();
            } else {
                horsechess.client.gui.GUIClient.lblMessage.setText(player.getUsername() + " cannot moved the horse");
            }

        }
    }
    public JLabel picChessMan;
    //Custom variable
    //Current position
    // private Point positionGUI;
    //name of file Picture of chessman
    private String fileName;
    //State of click
    private Boolean stateClick;
    //Data of player
    private PlayerData player;
    //Data of chessboard
    private ChessBoardData chessBoard;
    //Data of chessman
    private ChessManData chessMan;


    //Getter && Setter
    public ChessBoardData getChessBoard() {
        return chessBoard;
    }

    public void setChessBoard(ChessBoardData chessBoard) {
        this.chessBoard = chessBoard;
    }

    public ChessManData getChessMan() {
        return chessMan;
    }

    public void setChessMan(ChessManData chessMan) {
        this.chessMan = chessMan;
    }

    public PlayerData getPlayer() {
        return player;
    }

    public void setPlayer(PlayerData player) {
        this.player = player;
    }
}
